﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEditor;
using System.Linq;

public class XCodeProjectBuilder
{
    public static void CommandLineArgsRun()
    {
        var args = System.Environment.GetCommandLineArgs();
        if (args.Length <= 0)
        {
            EditorApplication.Exit(1);
        }

        var path = string.Empty;
        foreach (var item in args)
        {
            Debug.Log("Canshu !!!!!!!!!!!! = "+ item);
            if (item.StartsWith("JenkinsArgs;"))
            {
                path = item.Replace("JenkinsArgs;","");
                break;
            }
        }

        var arr = path.Split(';');
        XCodeProjectMod.CurrentBuildChannelName = arr[0];
        path = arr[1];
        if (Directory.Exists(path))
        {
            Debug.LogError("导出目录已经存在：" + path);
            Directory.Delete(path, true);
        }
        Debug.Log("Path:" + path);
        BuildXCodeProject(path);
    }

    public static void BuildXCodeProject(string TargetFolder)
    {
        if (!string.IsNullOrEmpty(TargetFolder))
        {
            if (Directory.Exists(TargetFolder))
            {
                Debug.LogError("导出目录已经存在："+TargetFolder);
                return;
            }
            Debug.LogError("Xcode工程输出目录：" + TargetFolder);
            Directory.CreateDirectory(TargetFolder);
            UnityEditor.BuildPipeline.BuildPlayer(GetBuildScenes(), TargetFolder, BuildTarget.iOS, GetBuildOptions());
        }
    }

    private static string[] GetBuildScenes()
    {
        return EditorBuildSettings.scenes.Where(s => (s != null && s.enabled)).Select(s => s.path).ToArray();
    }

    private static BuildOptions GetBuildOptions()
    {
        var buildOption = BuildOptions.None;

        if (EditorUserBuildSettings.development)
        {
            buildOption |= BuildOptions.Development;
        }

        if (EditorUserBuildSettings.connectProfiler)
        {
            buildOption |= BuildOptions.ConnectWithProfiler;
        }

        if (EditorUserBuildSettings.allowDebugging)
        {
            buildOption |= BuildOptions.AllowDebugging;
        }

        if (EditorUserBuildSettings.symlinkLibraries)
        {
            buildOption |= BuildOptions.SymlinkLibraries;
        }

        return buildOption;
    }
}
